package com.gridmobi.xrtb.job;

import com.gridmobi.xrtb.common.ExecutorPool;
import com.gridmobi.xrtb.component.lucene.BidIndex;
import com.gridmobi.xrtb.domain.dsp.DspCampaigns;
import com.gridmobi.xrtb.domain.dsp.common.OpenApiParamDTO;
import com.gridmobi.xrtb.domain.dsp.common.OpenApiResponseDTO;
import com.gridmobi.xrtb.domain.dsp.common.enums.DelFlagE;
import com.gridmobi.xrtb.domain.dsp.common.enums.StateE;
import com.gridmobi.xrtb.handler.DataSynchHandler;
import com.gridmobi.xrtb.handler.monitor.RtbStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.time.Instant;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * 本地内存索引初始化的JOB
 * 此JOB 不运行完毕系统不能参与RTB
 *
 * @author huangyongchao
 */
@Component
public class InitIndexJob {
    private static final Logger logger = LoggerFactory.getLogger(InitIndexJob.class);

    /**
     * 索引初始化状态,初始完毕才可以参与Rtb
     */
    public static final Date INDEX_INIT_TIMESTAMP_END = Date.from(Instant.parse("2018-11-23T10:12:35Z"));
    public static final Date INDEX_INIT_TIMESTAMP_START = Date.from(Instant.parse("2018-11-23T10:12:35Z"));
    @Value("${luceneindex.synch.pagesize}")
    public static Integer DATA_QUERY_PAGESIZE = 3000;

    @Autowired
    private DataSynchHandler dataSynch;

    @Autowired
    private BidIndex bidIndex;

    @PostConstruct
    public void init() {
        initData();
        /*
        初始完毕 设置初始状态为 true,可以参与竞价
         */
        RtbStatus.INDEX_INIT_FINISHED.set(true);
    }

    /**
     * 初始化之前清掉索引文件,非RAM存储
     * 避免脏数据
     *
     * @throws IOException
     */
    private void clearData() throws IOException {
        BidIndex.CAMPAIGNS_W.deleteAll();

        BidIndex.CREATIVES_W.deleteAll();
        BidIndex.CAMPAIGNS_SCHE_W.deleteAll();
    }

    /**
     * 初始化索引
     */
    private void initData() {
        try {

            clearData();

            /**
             * 暂时没有分页查询 后续数据量大的时候改进 bugflag
             * 并发执行 注意线程数要和count latch 个数一致
             */

            CountDownLatch countDownLatch = new CountDownLatch(5);


            OpenApiParamDTO p1 = new OpenApiParamDTO();
            p1.setStart(INDEX_INIT_TIMESTAMP_START);
            p1.setEnd(INDEX_INIT_TIMESTAMP_END);
            p1.setSize(DATA_QUERY_PAGESIZE);
            p1.setDelstate(DelFlagE.NO.code);
            p1.setState(StateE.VALID.code);

            ExecutorPool.getExecutor().execute(()->{
                try {
                    OpenApiResponseDTO<DspCampaigns> campaignsResponse = dataSynch.synchCampaigns(p1);
                    if (campaignsResponse != null && campaignsResponse.getDatas() != null) {
                        bidIndex.indexCampaigns(campaignsResponse.getDatas());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("",e);
                }finally {
                    countDownLatch.countDown();

                }
            });

            ExecutorPool.getExecutor().execute(()->{
                try {
                    bidIndex.indexCreatives(dataSynch.convertBannerList(dataSynch.synchCreativeBanner(p1)));
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("",e);
                }finally {
                    countDownLatch.countDown();

                }
            });

            ExecutorPool.getExecutor().execute(()->{
                try {
                    bidIndex.indexCreatives(dataSynch.convertVideoList(dataSynch.synchCreativeVideo(p1)));
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("",e);
                }finally {
                    countDownLatch.countDown();

                }
            });

            ExecutorPool.getExecutor().execute(()->{
                try {
                    bidIndex.indexCreativesNative(dataSynch.synchCreativeNative(p1));
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("",e);
                    countDownLatch.countDown();
                }finally {
                    countDownLatch.countDown();

                }
            });


            ExecutorPool.getExecutor().execute(()->{
                try {
                    bidIndex.indexCreatives(dataSynch.convertHtmlList(dataSynch.synchCreativeHtml(p1)));
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("",e);
                    countDownLatch.countDown();
                }finally {
                    countDownLatch.countDown();

                }
            });



            ExecutorPool.getExecutor().execute(()->{
                try {
                    OpenApiResponseDTO microBidResponse = dataSynch.synchMicroBid(p1);
                    bidIndex.indexMicroBid(microBidResponse.getDatas());
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("",e);
                }finally {
                    countDownLatch.countDown();

                }
            });

            ExecutorPool.getExecutor().execute(()->{
                try {
                    OpenApiResponseDTO blockResponse= dataSynch.synchBlocklist(p1);
                    bidIndex.indexBlockList(blockResponse.getDatas());
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("",e);
                }finally {
                    countDownLatch.countDown();

                }
            });

            countDownLatch.await();


        } catch (Exception e) {
            e.printStackTrace();
            logger.error("",e);

        }

    }
}
